package com.bite.common.core.utils;

import com.bite.common.core.constants.JwtConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.HashMap;
import java.util.Map;

public class JwtUtils {
    /**
     *
     * ⽣成令牌
     *
     * @param claims 数据
     * @param secret 密钥
     * @return 令牌
     */

    public static String createToken(Map<String, Object> claims, String secret)
    {
        String token =
                Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512,
                        secret).compact();
        return token;
    }
    /**
     *
     * 从令牌中获取数据
     *
     * @param token 令牌
     * @param secret 密钥
     * @return数据
     */
    public static Claims parseToken(String token, String secret) {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
        Claims claims =claimsJws.getBody();
        return claims;

    }

    public static String getUserKey(Claims claims) {
        return toStr(claims.get(JwtConstants.LOGIN_USER_KEY));
    }

    public static String getUserId(Claims claims) {
        return toStr(claims.get(JwtConstants.LOGIN_USER_ID));

    }

    private static String toStr(Object value) {
        if (value == null){
            return "";
        }
        return value.toString();
    }

    public static void main(String[] args) {
        Map<String,Object> map = new HashMap<>();
        map.put("userId",123456789L);
        System.out.println(createToken(map, "zxcvbnmasdfghiuiyreqtuiwg"));
//        String token ="eyJhbGciOiJIUzUxMiJ9.eyJ1c2VySWQiOjEsInVzZXJLZXkiOiJiNzQ2MTI2YS1kMWMyLTQzMTAtYWM5YS0yZmVkZmUzNDEzYjYifQ.oMeYBrC083HBwPupkT9Vkg8G-20N1leEmBM9KrfK2Z05LK2LywfqYrIO8i--7sRsNhwZWiaXfVZcfowXnrqPmg";
        String token = "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VySWQiOjEyMzQ1Njc4OX0.lbEad5CXN3_k3QHSsGgLIeHtpwcH30zvfdd_ch5tBTuPwy7EapYgrXCBpjd6lxuNbO3PM38nB5EzEHPbK3oZYg";
        System.out.println(parseToken(token, "zxcvbnmasdfghiuiyreqtuiwg"));
    }
}

